package com.ruoyi.system.service.impl;

import com.alipay.api.AlipayApiException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwEnterpriseInfo;
import com.ruoyi.system.domain.GwPlatformAccount;
import com.ruoyi.system.domain.GwPlatformRights;
import com.ruoyi.system.domain.GwPlatformRightsOrder;
import com.ruoyi.system.domain.vo.PlatformRightsOrderVO;
import com.ruoyi.system.domain.vo.WxPayResultVO;
import com.ruoyi.system.mapper.GwEnterpriseInfoMapper;
import com.ruoyi.system.mapper.GwPlatformRightsMapper;
import com.ruoyi.system.mapper.GwPlatformRightsOrderMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.BaseService;
import com.ruoyi.system.service.IGwPlatformAccountService;
import com.ruoyi.system.service.IGwPlatformRightsOrderService;
import com.ruoyi.system.service.WeChatPayService;
import com.ruoyi.system.utils.AlipayUtil;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 平台权益订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-12
 */
@Service
public class GwPlatformRightsOrderServiceImpl extends BaseService implements IGwPlatformRightsOrderService
{
    private static final Logger log = LoggerFactory.getLogger(GwPlatformRightsOrderServiceImpl.class);
    @Resource
    private GwPlatformRightsOrderMapper gwPlatformRightsOrderMapper;
    @Resource
    private GwPlatformRightsMapper gwPlatformRightsMapper;
    @Resource
    private GwEnterpriseInfoMapper enterpriseInfoMapper;
    @Resource
    private WeChatPayService wxChatPayService;
    @Value("${wx.pay.rightsNotifyUrl}")
    private String rightsNotifyUrl;

    @Value("${alipay.rightsNotifyUrl}")
    private String alipayRightsReturnUrl;

    @Value("${alipay.rightsReturnUrl}")
    private String alipayRightsNotifyUrl;

    @Autowired
    private AlipayUtil alipayUtil;
    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private IGwPlatformAccountService platformAccountService;

    /**
     * 查询平台权益订单
     * 
     * @param id 平台权益订单主键
     * @return 平台权益订单
     */
    @Override
    public GwPlatformRightsOrder selectGwPlatformRightsOrderById(String id)
    {
        return gwPlatformRightsOrderMapper.selectGwPlatformRightsOrderById(id);
    }

    /**
     * 查询平台权益订单列表
     * 
     * @param gwPlatformRightsOrder 平台权益订单
     * @return 平台权益订单
     */
    @Override
    public List<GwPlatformRightsOrder> selectGwPlatformRightsOrderList(GwPlatformRightsOrder gwPlatformRightsOrder)
    {
        return gwPlatformRightsOrderMapper.selectGwPlatformRightsOrderList(gwPlatformRightsOrder);
    }

    /**
     * 新增平台权益订单
     * 
     * @param gwPlatformRightsOrder 平台权益订单
     * @return 结果
     */
    @Override
    public int insertGwPlatformRightsOrder(GwPlatformRightsOrder gwPlatformRightsOrder)
    {
        gwPlatformRightsOrder.setId(IdUtils.fastSimpleUUID());
        gwPlatformRightsOrder.setOrderNumber(createOrderNumber());
        gwPlatformRightsOrder.setCreateTime(DateUtils.getNowDate());
        gwPlatformRightsOrder.setCreateBy(SecurityUtils.getUserId()+"");
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        if(sysUser!=null){
            gwPlatformRightsOrder.setPhone(sysUser.getPhonenumber());
        }
        int num = gwPlatformRightsOrderMapper.insertGwPlatformRightsOrder(gwPlatformRightsOrder);
        return num;
    }

    /**
     * 修改平台权益订单
     * 
     * @param gwPlatformRightsOrder 平台权益订单
     * @return 结果
     */
    @Override
    public int updateGwPlatformRightsOrder(GwPlatformRightsOrder gwPlatformRightsOrder)
    {
        gwPlatformRightsOrder.setUpdateTime(DateUtils.getNowDate());
        return gwPlatformRightsOrderMapper.updateGwPlatformRightsOrder(gwPlatformRightsOrder);
    }

    /**
     * 批量删除平台权益订单
     * 
     * @param ids 需要删除的平台权益订单主键
     * @return 结果
     */
    @Override
    public int deleteGwPlatformRightsOrderByIds(String[] ids)
    {
        return gwPlatformRightsOrderMapper.deleteGwPlatformRightsOrderByIds(ids);
    }

    /**
     * 删除平台权益订单信息
     * 
     * @param id 平台权益订单主键
     * @return 结果
     */
    @Override
    public int deleteGwPlatformRightsOrderById(String id)
    {
        return gwPlatformRightsOrderMapper.deleteGwPlatformRightsOrderById(id);
    }

    @Override
    public List<PlatformRightsOrderVO> selectList(GwPlatformRightsOrder gwPlatformRightsOrder) {
        if(StringUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            gwPlatformRightsOrder.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        }
        if(StringUtils.isNotEmpty(gwPlatformRightsOrder.getStatus()) && gwPlatformRightsOrder.getStatus().equals("0")){
            gwPlatformRightsOrder.setStatus(null);
        }
        return gwPlatformRightsOrderMapper.selectList(gwPlatformRightsOrder);
    }

    /**
     * 购买套餐
     * @Date 下午 2:58:54 2025/5/28
     * @param gwPlatformRightsOrder
     * @return 结果
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult payOrder(GwPlatformRightsOrder gwPlatformRightsOrder)  {
        AjaxResult ajaxResult = new AjaxResult();
        if(StringUtils.isBlank(SecurityUtils.getLoginUser().getEnterpriseId())){
            return AjaxResult.error("当前用户未关联任何企业，无法购买！");
        }
        GwEnterpriseInfo gwEnterpriseInfo = enterpriseInfoMapper.selectGwEnterpriseInfoById(SecurityUtils.getLoginUser().getEnterpriseId());
        if(gwEnterpriseInfo==null){
            return AjaxResult.error("未查询到操作人所在企业信息！");
        }
        GwPlatformRights originRight = gwPlatformRightsMapper.selectGwPlatformRightsById(gwPlatformRightsOrder.getRightsId());
        gwPlatformRightsOrder.setOrderNumber(createOrderNumber());
        gwPlatformRightsOrder.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        gwPlatformRightsOrder.setAmount(new BigDecimal(originRight.getPrice()));
        gwPlatformRightsOrder.setPayTime(new Date());
        gwPlatformRightsOrder.setStatus(OrderStatus.WAIT.getCode());
        gwPlatformRightsOrder.setId(IdUtils.fastSimpleUUID());
        gwPlatformRightsOrder.setPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
        gwPlatformRightsOrderMapper.insertGwPlatformRightsOrder(gwPlatformRightsOrder);

        if(gwPlatformRightsOrder.getPayType().equals(PayType.WEI_XIN.getCode())){
            String codeUrl =  wxChatPayService.createNativePayOrder(gwPlatformRightsOrder.getId(), new BigDecimal(originRight.getPrice()).multiply(new BigDecimal(100)).intValue(),
                    originRight.getRightName(), rightsNotifyUrl);
            ajaxResult.put("orderId",gwPlatformRightsOrder.getId());
            ajaxResult.put("path",codeUrl);
            return ajaxResult;
        }else if(gwPlatformRightsOrder.getPayType().equals(PayType.ZHI_FU_BAO.getCode())){
            String form = null;
            try {
                form = alipayUtil.createPayPage(gwPlatformRightsOrder.getId(), originRight.getRightName(), originRight.getPrice(),alipayRightsReturnUrl,alipayRightsNotifyUrl);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            ajaxResult.put("orderId",gwPlatformRightsOrder.getId());
            ajaxResult.put("path",form);
            return ajaxResult;
        }else{
            return AjaxResult.error("支付方式不识别！");
        }

    }

    @Override
    public List<PlatformRightsOrderVO> orderList(GwPlatformRightsOrder gwPlatformRightsOrder) {
        if(StringUtils.isBlank(SecurityUtils.getLoginUser().getEnterpriseId())){
            return Lists.newArrayList();
        }
        gwPlatformRightsOrder.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        gwPlatformRightsOrder.setStatus(OrderStatus.PAY.getCode());
        return gwPlatformRightsOrderMapper.selectList(gwPlatformRightsOrder);
    }

    @Override
    public AjaxResult appletPayOrder(GwPlatformRightsOrder gwPlatformRightsOrder){
        String enterpriseId = "";
        if(StringUtils.isBlank(gwPlatformRightsOrder.getUserId())){
            return AjaxResult.error("当前用户未关联任何企业，无法购买！");
        }else{
            SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(gwPlatformRightsOrder.getUserId()));
            if(sysUser!=null){
                enterpriseId = getEnterpriseId(sysUser);
            }
            if(StringUtils.isEmpty(enterpriseId)){
                return AjaxResult.error("当前用户未关联任何企业，无法购买！");
            }
        }
        GwEnterpriseInfo gwEnterpriseInfo = enterpriseInfoMapper.selectGwEnterpriseInfoById(enterpriseId);
        if(gwEnterpriseInfo==null){
            return AjaxResult.error("未查询到操作人所在企业信息！");
        }

        GwPlatformRights originRight = gwPlatformRightsMapper.selectGwPlatformRightsById(gwPlatformRightsOrder.getRightsId());
        gwPlatformRightsOrder.setOrderNumber(createOrderNumber());
        gwPlatformRightsOrder.setEnterpriseId(enterpriseId);
        gwPlatformRightsOrder.setAmount(new BigDecimal(originRight.getPrice()));
        gwPlatformRightsOrder.setPayTime(new Date());
        gwPlatformRightsOrder.setStatus(OrderStatus.WAIT.getCode());
        gwPlatformRightsOrder.setId(IdUtils.fastSimpleUUID());
        gwPlatformRightsOrder.setPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
        gwPlatformRightsOrderMapper.insertGwPlatformRightsOrder(gwPlatformRightsOrder);
            Map<String,String> paramsMap = null;
            try {
                paramsMap = wxChatPayService.createAppletPrepayOrder(gwPlatformRightsOrder.getId(), new BigDecimal(originRight.getPrice()).multiply(new BigDecimal(100)).intValue(),
                        originRight.getRightName(), rightsNotifyUrl,gwPlatformRightsOrder.getOpenId());
            } catch (Exception e) {
                log.error("系统出现异常:{}",e.getMessage());
                return AjaxResult.error("系统出现异常，请稍后再试！");
            }
            return AjaxResult.success(paramsMap);

    }

    private String getEnterpriseId(SysUser sysUser){
        String userType = sysUser.getUserType();

        if(userType.equals(UserType.SYSTEM_USER.getCode())|| userType.equals(UserType.OPERATION_USER.getCode())
                ||  userType.equals(UserType.AGENT_USER.getCode())){
            return null;
        }
        if(userType.equals(UserType.PLATFORM_USER.getCode()) && !StringUtils.isEmpty(sysUser.getChannelId())){
            GwPlatformAccount account = platformAccountService.selectGwPlatformAccountById(sysUser.getChannelId());
            return account!=null?account.getEnterpriseId():null;
        }else if(userType.equals(UserType.ENTERPRISE_USER.getCode()) && !StringUtils.isEmpty(sysUser.getChannelId())){
            return sysUser.getChannelId();
        }
        return null;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleRightsOrder(WxPayResultVO wxPayResultVO) {
        if(wxPayResultVO!=null && wxPayResultVO.getTradeState().equals(WxPayState.SUCCESS.getCode())){
            //支付成功，更新购买套餐后的有效期、合同、短信条数
            GwPlatformRightsOrder rightsOrder =  gwPlatformRightsOrderMapper.selectGwPlatformRightsOrderById(wxPayResultVO.getOutTradeNo());
            if(rightsOrder!=null && !StringUtils.isBlank(rightsOrder.getRightsId()) && rightsOrder.getStatus().equals(OrderStatus.WAIT.getCode())){
                GwPlatformRights originRight =  gwPlatformRightsMapper.selectGwPlatformRightsById(rightsOrder.getRightsId());
                GwEnterpriseInfo gwEnterpriseInfo =  enterpriseInfoMapper.selectGwEnterpriseInfoById(rightsOrder.getEnterpriseId());
                //计算购买套餐后的有效期、合同、短信条数
                if(originRight.getBusinessType().equals(RightType.USE_TIME.getCode())){
                    //判断该企业有效期是否过期，未过期，从失效期开始加权益天数，已过期，从当前日期开始加权益天数
                    if(gwEnterpriseInfo.getEffectiveTime()==null || gwEnterpriseInfo.getEffectiveTime().before(new Date())){
                        gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(originRight.getAmount()));
                    }else{
                        gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(gwEnterpriseInfo.getEffectiveTime(),originRight.getAmount()));
                    }
                    //判断该使用时长是否有赠送合同和短信
                    if(originRight.getGiftContract()!=null && originRight.getGiftContract()>0){
                        gwEnterpriseInfo.setContractAllNum(gwEnterpriseInfo.getContractAllNum()+originRight.getGiftContract());
                    }
                    if(originRight.getGiftSms()!=null && originRight.getGiftSms()>0){
                        gwEnterpriseInfo.setSmsAllNum(gwEnterpriseInfo.getSmsAllNum()+originRight.getGiftSms());
                    }
                }else if(originRight.getBusinessType().equals(RightType.CONTRACT.getCode())){
                    gwEnterpriseInfo.setContractAllNum(gwEnterpriseInfo.getContractAllNum()+originRight.getAmount());
                }else if(originRight.getBusinessType().equals(RightType.SMS.getCode())){
                    gwEnterpriseInfo.setSmsAllNum(gwEnterpriseInfo.getSmsAllNum()+originRight.getAmount());
                }
                gwEnterpriseInfo.setVersionType("2");
                enterpriseInfoMapper.updateGwEnterpriseInfo(gwEnterpriseInfo);
                //更新订单状态
                rightsOrder.setStatus(OrderStatus.PAY.getCode());
                rightsOrder.setPayTime(DateUtils.parseDate(wxPayResultVO.getSuccessTime()));
                rightsOrder.setTransactionId(wxPayResultVO.getTransactionId());
                gwPlatformRightsOrderMapper.updateGwPlatformRightsOrder(rightsOrder);
            }
        }
    }

    @Override
    public void handleRightsOrderByAlipay(String outTradeNo, String tradeNo, String gmtPayment) {
        //支付成功，更新购买套餐后的有效期、合同、短信条数
        GwPlatformRightsOrder rightsOrder =  gwPlatformRightsOrderMapper.selectGwPlatformRightsOrderById(outTradeNo);
        if(rightsOrder!=null && !StringUtils.isBlank(rightsOrder.getRightsId())){
            GwPlatformRights originRight =  gwPlatformRightsMapper.selectGwPlatformRightsById(rightsOrder.getRightsId());
            GwEnterpriseInfo gwEnterpriseInfo =  enterpriseInfoMapper.selectGwEnterpriseInfoById(rightsOrder.getEnterpriseId());
            //计算购买套餐后的有效期、合同、短信条数
            if(originRight.getBusinessType().equals(RightType.USE_TIME.getCode())){
                //判断该企业有效期是否过期，未过期，从失效期开始加权益天数，已过期，从当前日期开始加权益天数
                if(gwEnterpriseInfo.getEffectiveTime()==null || gwEnterpriseInfo.getEffectiveTime().before(new Date())){
                    gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(originRight.getAmount()));
                }else{
                    gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(gwEnterpriseInfo.getEffectiveTime(),originRight.getAmount()));
                }
                //判断该使用时长是否有赠送合同和短信
                if(originRight.getGiftContract()!=null && originRight.getGiftContract()>0){
                    gwEnterpriseInfo.setContractAllNum(gwEnterpriseInfo.getContractAllNum()+originRight.getGiftContract());
                }
                if(originRight.getGiftSms()!=null && originRight.getGiftSms()>0){
                    gwEnterpriseInfo.setSmsAllNum(gwEnterpriseInfo.getSmsAllNum()+originRight.getGiftSms());
                }
            }else if(originRight.getBusinessType().equals(RightType.CONTRACT.getCode())){
                gwEnterpriseInfo.setContractAllNum(gwEnterpriseInfo.getContractAllNum()+originRight.getAmount());
            }else if(originRight.getBusinessType().equals(RightType.SMS.getCode())){
                gwEnterpriseInfo.setSmsAllNum(gwEnterpriseInfo.getSmsAllNum()+originRight.getAmount());
            }
            gwEnterpriseInfo.setVersionType("2");
            enterpriseInfoMapper.updateGwEnterpriseInfo(gwEnterpriseInfo);
            //更新订单状态
            rightsOrder.setStatus(OrderStatus.PAY.getCode());
            rightsOrder.setPayTime(DateUtils.parseDate(gmtPayment));
            rightsOrder.setTransactionId(tradeNo);
            gwPlatformRightsOrderMapper.updateGwPlatformRightsOrder(rightsOrder);
        }
    }


    private String createOrderNumber(){
        String orderNumber = "V";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String time = sdf.format(new Date());
        orderNumber=orderNumber+time;
        //4位随机数
        Random random = new Random();
        int min = 1000;
        int max = 9999;
        int randomNum = random.nextInt(max - min + 1) + min;
        orderNumber = orderNumber+randomNum;
        return orderNumber;
    }
}
